﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RollBall : MonoBehaviour {

    public static RollBall Instance;

    //移动速度
    private int speed = 500;
    private Rigidbody rigidbody;
    private AudioSource audios;

    public AudioClip RollClip;

    [HideInInspector]
    public bool canRoll = true;
    [HideInInspector]
    public bool playClip = false;

    private void Start()
    {
        Instance = this;
        audios = GameObject.Find("GroundPlane").GetComponent<AudioSource>();
        rigidbody = gameObject.GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (canRoll==true)
        {
            //建立一个向量变量，将手机向量坐标改变为游戏向量坐标
            Vector3 dir = Vector3.zero;
            dir.z = Input.acceleration.y;
            dir.x = Input.acceleration.x;

            //钳制加速度向量到单位球
            if (dir.sqrMagnitude > 1)
                dir.Normalize();

            //使它每秒移动10米，而不是每帧10米
            dir *= Time.deltaTime;

            // Move object 移动物体
            rigidbody.AddForce(dir * speed, ForceMode.Force);

            if (rigidbody.velocity == new Vector3(0, 0, 0))
            {
                audios.Stop();
                playClip = false;
            }
            else if (rigidbody.velocity != new Vector3(0, 0, 0) && playClip==false)
            {
                audios.Play();
                audios.loop = true;
                playClip = true;
            }
        }
        
    }
}
